package com.cictec.middleware.tde.rm.disp.receiver.handler;

import java.util.Date;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cictec.middleware.commons.utils.Result;
import com.cictec.middleware.commons.utils.ResultUtil;
import com.cictec.middleware.feign.distribute.MiddlewareDeviceService;
import com.cictec.middleware.tde.rm.SessionManager;
import com.cictec.middleware.tde.rm.disp.annotation.HandleMessages;
import com.cictec.middleware.tde.rm.disp.receiver.AbstractReceiverHandler;
import com.cictec.middleware.tde.rm.protocol.TerminalMessage;
import com.cictec.middleware.tde.rm.protocol.TerminalMessage.Header;
import com.cictec.middleware.tde.rm.protocol.rm.message.Rm0x4ATerminalMessage;
import com.cictec.middleware.tde.rm.protocol.rm.message.Rm0xCAPlatformMessage;

/**
 * 设备编号查询
 */
@Component
@HandleMessages(0X4A)
public class TerminalIdQueryHandler extends AbstractReceiverHandler {

	private static Logger logger = LoggerFactory.getLogger(TerminalIdQueryHandler.class);

	@Autowired
	private SessionManager sessionManager;
	@Autowired
	private MiddlewareDeviceService middlewareDeviceService;

	@Override
	public void handleMessage(TerminalMessage message, IoSession session) {

		Rm0x4ATerminalMessage msg = (Rm0x4ATerminalMessage) message;
		
//		oldHandler(msg, session);	// 老逻辑处理
		
		// 新逻辑只做回复
		logger.debug("【0X4A设备编号查询】终端 {}  Session {} ", msg.getManuId(), msg.getSessionId());
		Rm0xCAPlatformMessage responseMsg = createPlatformIdResponse(msg);
		try {
			session.write(responseMsg);
			logger.debug("【0X4A设备编号查询】终端 {}  Session {} 回复上传指令成功  !", msg.getTerminalId(), msg.getSessionId());
		} catch (Exception e) {
			e.printStackTrace();
			logger.debug("【0X4A设备编号查询】终端 {}  Session {} 回复上传指令失败  :{}", msg.getTerminalId(), msg.getSessionId(), e);
		}

	}

	/**
	 * 老的逻辑里边4A做了业务处理，新的4A什么都不做，统一放在01里边做
	 * @param msg
	 */
	private void oldHandler(Rm0x4ATerminalMessage msg, IoSession session){
		String terminalId = msg.getTerminalId();
		String tid = msg.getManuId();

		logger.debug("【0X4A设备编号查询】终端 {}  Session {} ", msg.getManuId(), msg.getSessionId());

		// Device device = deviceService.selectDeviceByDevCode(tid);

		Result result = middlewareDeviceService.deviceConnectByDevcode(tid);
		if (ResultUtil.isSuccess(result)) {
			// 成功找到设备信息
			if (logger.isDebugEnabled()) {
				logger.info("【0X4A设备编号查询】终端 {}  Session {} 对应的终端ID 为 {}", terminalId, msg.getSessionId(), tid);
			}

			String serialNumber = sessionManager.getSerialNumber(session);
			if (logger.isDebugEnabled()) {
				logger.debug("【0X4A设备编号查询】终端 {}  Session {} 对应的SerialNumber为 {}", terminalId, msg.getSessionId(), serialNumber);
			}

			if (serialNumber != null) {
				// 没有设备SN的注册信息。
				middlewareDeviceService.updateDeviceSerialNumber(terminalId, serialNumber);
			}

			Rm0xCAPlatformMessage responseMsg = createPlatformIdResponse(msg);

			try {
				session.write(responseMsg);
				logger.debug("【0X4A设备编号查询】终端 {}  Session {} 回复上传指令成功  !", terminalId, msg.getSessionId());
			} catch (Exception e) {
				e.printStackTrace();
				logger.debug("【0X4A设备编号查询】终端 {}  Session {} 回复上传指令失败  :{}", terminalId, msg.getSessionId(), e);
			}

			if (sessionManager.getTerminalId(session) == null) {
				// 向session中注册该设备
				sessionManager.tmpToRegistered(msg.getSessionId(), tid);

				/* **** 设置位置数据上传的时间间隔 start ************************/
				sendMessageToTerminal(createUploadInterval(msg), session);
				/* ******** 设置位置数据上传的时间间隔 end ****************************/
				logger.debug("【0X4A设备编号查询】终端 {}  Session {} 设置位置数据上传时间间隔  ", terminalId, msg.getSessionId());
			}

		} else {
			logger.debug("【0X4A设备编号查询】终端 {}  Session {} 找不到设备编号  {}  对应的设备, session被关闭", msg.getManuId(), msg.getSessionId(), tid);
			sessionManager.closeSession(session);
		}
	}
	
	/**
	 * 【0xCA】创建 0x4A的回复指令
	 * 
	 * @param message
	 * @return
	 */
	private Rm0xCAPlatformMessage createPlatformIdResponse(Rm0x4ATerminalMessage message) {
		int id = Integer.valueOf(message.getManuId());

		Header header = new Header(0xCA);
		header.setSendTime(new Date());
		header.setLineId(message.getHeader().getLineId());
		// header.setTerminalId(tiq.getHeader().getTerminalId());
		header.setTerminalId(id); // 返回原始的设备编号
		header.setDataFlag(0);

		Rm0xCAPlatformMessage msg = new Rm0xCAPlatformMessage(header);
		msg.setResponseTime(new Date());
		msg.setId(id);
		msg.setSessionId(message.getSessionId());

		return msg;
	}
	
	
}
